<template>
  <div class="app-container documentation-container">

<div  >
  

<p>
    <span style=""><strong>艺术家主页展示短视频（最多5个）</strong></span>
</p>

<div style="font-size:14px">
<p>
    <span style="">长度：单个视频长度在1分钟内,可用手机录像或抖音制作</span>
</p>
<p>
    <span style="">内容：主要拍摄作品，背景音可选择音乐或口述作品创作故事；一起和支持者们分享你绘画路上印象深刻的那些记忆吧。</span>
</p>
</div>
<p>
    <span style=""><br/></span>
</p>


<p>
    <span style="">上传视频</span>
</p>
<van-uploader  accept="video/*"	  name="shopvideo" :after-read="uploadvideo"  v-model="videolist" multiple :max-count="5" preview-size="200px"	/>

<!-- <van-uploader accept="video/*"	name="shopvideo" :after-read="uploadvideo"	 v-model="videolist" multiple :max-count="5" preview-size="200px"	>
  <div class="uploadarea">
  <div type="primary" class="uploadbtn">+</div>
  <div class="videoname">{{this.tempvideo.title}}</div>
  </div>
</van-uploader> -->


<div @click="savevideos" class="tjshipin">提交</div>


<p>
    <span style=""><br/></span>
</p>


<p>
    <span style="color:#ff0000">备注：短视频口述内容提示（可参考，请艺术家选择自己最有感触的回答）</span>
</p>
<p>
    <span style="font-size:12px">1.绘画灵感来自哪里，创作时有哪些顿悟？</span>
</p>
<p>
    <span style="font-size:12px">2.是什么契机开始学习绘画的？</span>
</p>
<p>
    <span style="font-size:12px">3.你认为对于画家来说，最有趣的事情是什么？</span>
</p>
<p>
    <span style="font-size:12px">4.有没有想过放弃绘画的时刻，当时是发生了什么？</span>
</p>
<p>
    <span style="font-size:12px">5.自己最满意的作品是哪一幅，接下来想创作怎样的作品？</span>
</p>
<p>
    <span style="font-size:12px">6.关于绘画是否有过有趣的、搞笑的、悲伤的、震惊的、让你难忘的事情？</span>
</p>
<p>
    <span style="font-size:12px">7.日常生活中，感觉画家观察世界的方式和其他人有什么区别？</span>
</p>
<p>
    <span style="font-size:12px">8.艺术是否给你的生活带来了哪些变化（友谊、爱情皆可）？</span>
</p>
<p>
    <br/>
</p>

 
   
  </div>
<van-popup v-model="videoinfo">
<van-cell-group>
  <van-field
    v-model="tempvideo.title"
    required
    clearable
    label="用户名"
    right-icon="question-o"
    placeholder="请输入用户名"
    @click-right-icon="$toast('question')"
  />

  <van-field
    v-model="tempvideo.desc"
    type="password"
    label="密码"
    placeholder="请输入密码"
    required
  />
</van-cell-group>

 </van-popup>


  </div>
</template>

<script>
import DropdownMenu from '@/components/Share/DropdownMenu'
import { mapGetters } from 'vuex'
import {Circle, Popup} from 'vant'
import Vue from 'vue'
 
import { Uploader,Cell,CellGroup } from 'vant'
Vue.use(Uploader).use(Cell).use(CellGroup);
import digitaSign from '@/components/page/case/digitaSign';
 Vue.use(Circle);
Vue.use(Popup)
import { gettokens,getvideoinfo,addshopvideo} from "@/api/user";
import { clearInterval } from 'timers';

 
 
export default {
  name: 'shipin',
  components: { DropdownMenu },
    computed: {
    ...mapGetters([
      'name',
      'avatar',
      'roles',
      'cardname',
      'introduction'
    ])
  },
  data() {
    return {
      
      timer:null,
      videoinfo:false,
      videolist:[        
     
        // Uploader 根据文件后缀来判断是否为图片文件
        // 如果图片 URL 中不包含类型信息，可以添加 isImage 标记来声明
        // { url: 'https://cloud-image', isImage: true }
        ],
      vid:'',
      havesign:false,
      popcontent:null,
      sign:false,
      show2:false,
      show:false,
       currentRate:0,
            rate:100,
            rate2:2,
            text:'',
        uploadImage5: require('@/assets/images/case/signname.png'),
      //   fileList: [
      //   { url: 'https://img.yzcdn.cn/vant/cat.jpeg' },
      //   // Uploader 根据文件后缀来判断是否为图片文件
      //   // 如果图片 URL 中不包含类型信息，可以添加 isImage 标记来声明
      //   { url: 'https://cloud-image', isImage: true }
      // ],
      articleList: [
        { title: '基础篇', href: 'https://juejin.im/post/59097cd7a22b9d0065fb61d2' },
        { title: '登录权限篇', href: 'https://juejin.im/post/591aa14f570c35006961acac' },
        { title: '实战篇', href: 'https://juejin.im/post/593121aa0ce4630057f70d35' },
        { title: 'vue-admin-template 篇', href: 'https://juejin.im/post/595b4d776fb9a06bbe7dba56' },
        { title: 'v4.0 篇', href: 'https://juejin.im/post/5c92ff94f265da6128275a85' },
        { title: '自行封装 component', href: 'https://segmentfault.com/a/1190000009090836' },
        { title: '优雅的使用 icon', href: 'https://juejin.im/post/59bb864b5188257e7a427c09' },
        { title: 'webpack4（上）', href: 'https://juejin.im/post/59bb864b5188257e7a427c09' },
        { title: 'webpack4（下）', href: 'https://juejin.im/post/5b5d6d6f6fb9a04fea58aabc' }
      ],
             policytoreport:{},
            checked: true,
            imagelist:[],
            imagelist1:[],
            imagelist2:[],
            imagelist3:[],
            imagelist4:[],
           
             uploader:null,
            carda:null,
            cardb:null,
            uploadtag:0,
            show:false,
            currentRate:0,
            rate:100,
             speed:100,
             text:'0%',
             tempvideo:{title:'',desc:''},
    }
  },
  components:{
digitaSign

  },
  mounted(){
     this.inituploader();
      // if(sessionStorage.getItem('signpic')&&sessionStorage.getItem('signpic')!='null')
      // {
      //   this.uploadImage5=sessionStorage.getItem('signpic')
      //   this.sign=true;
      // }

  },
  methods:{
     uploadvideo(event,detail) {
      var userData = "";
     console.log(event)
       var tt=detail.name;
       console.log("tt:"+tt)
       if(tt.indexOf("shopvideo")!=-1)
       this.uploadtag=1;
         if(tt.indexOf("att2")!=-1)
       this.uploadtag=2;
       if(tt.indexOf("att3")!=-1)
       this.uploadtag=3;
       if(tt.indexOf("att4")!=-1)
       this.uploadtag=4;

        if(tt.indexOf("carda")!=-1)
       this.uploadtag=5;
        if(tt.indexOf("cardb")!=-1)
       this.uploadtag=6;
       if(tt.indexOf("att5")!=-1)
       this.uploadtag=7;

    //  for (var i = 0; i < event.target.files.length; i++) {
        // 逻辑代码
        // userData = '{"Vod":{"UserData":"{"IsShowWaterMark":"false","Priority":"7"}"}}';
        /*userData = {
					Vod:{
						UserData:{
							IsShowWaterMark:false,
							Priority:7
						}
					}
        };*/
        console.log("0000000")
        console.log(event.file)
        var index=event.file.name.indexOf('.');
         this.tempvideo.title=event.file.name.substr(0,index);
        this.tempvideo.desc='这是描述'
          userData =
         '{"Vod":{"StorageLocation":"","Title":"'+this.tempvideo.title+'","Description":"this is desc.我是描述","CateId":"19","Tags":"tag1,tag2,标签3","fengmian":"http://www.baidu.com"}}';

        this.uploader.addFile(
         event.file,
          null,
          null,
          null,
          userData
        );
    //  }
      //  this.uploader.listFiles();
      // var list = this.uploader.listFiles();
      // for (var i=0; i<list.length; i++) {
      // alert("file:" + list[i].file.name + ", status:" + list[i].state + ", endpoint:" + list[i].endpoint + ", bucket:" + list[i].bucket + ", object:" + list[i].object);
      // }
        this.uploader.startUpload();
      //this.UpladFile(event.file);
    },
      inituploader() {
        
    var _this = this;
      this.uploader = new AliyunUpload.Vod({
        //分片大小默认1M，不能小于100K
        partSize: 1048576,
        //并行上传分片个数，默认5
        parallel: 5,
        //网络原因失败时，重新上传次数，默认为3
        retryCount: 3,
        //网络原因失败时，重新上传间隔时间，默认为2秒
        retryDuration: 2,
        // 开始上传
        onUploadstarted: function(uploadInfo) {
          _this.$loadingshowjindu('0%')
          console.log(
            "onUploadStarted:" +
              uploadInfo.file.name +
              ", endpoint:" +
              uploadInfo.endpoint +
              ", bucket:" +
              uploadInfo.bucket +
              ", object:" +
              uploadInfo.object
          );
          //上传方式1, 需要根据uploadInfo.videoId是否有值，调用点播的不同接口获取uploadauth和uploadAddress，如果videoId有值，调用刷新视频上传凭证接口，否则调用创建视频上传凭证接口
          // this.uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId);
          //上传方式2、

          //   $.ajax({
          //     url: "/api/getvideotoken",

          //     dataType: "json",
          //     type: "get",
          //     success: function(json) {
          //       //var uploadAddress = json.data.UploadAddress;
          //       //	var uploadAuth = json.data.UploadAuth;
          //       //var videoId = json.data.VideoId;
          //       //得到视频上传的凭证
          //       //vId = videoId;

          //       //如果此部分执行说明后端返回凭证成功，从data中获取返回的uploadAddress、uploadAuth、videoId，然后调用阿里云的api直接进行文件上传
          //       ///this.uploader.setUploadAuthAndAddress(uploadInfo, json.data.UploadAuth, json.data.UploadAddress, json.data.VideoId);
          //       this.uploader.setSTSToken(
          //         uploadInfo,
          //         json.result.key,
          //         json.result.secret,
          //         json.result.token
          //       );
          //     }
          //   });
          gettokens({}).then(res => {
              console.log(res)
              console.log(this.uploader)
            _this.uploader.setSTSToken(
              uploadInfo,
              res.result.key,
              res.result.secret,
              res.result.token
            );
          });
        },
        // 文件上传成功
        onUploadSucceed: function(uploadInfo) {
           _this.$loadingshowjindu( "100%")
            _this.$loadingshowjindu( "")
          console.log(
            "onUploadSucceed: " +
              uploadInfo.file.name +
              ", endpoint:" +
              uploadInfo.endpoint +
              ", bucket:" +
              uploadInfo.bucket +
              ", object:" +
              uploadInfo.object +
              uploadInfo +
              JSON.stringify(uploadInfo)
          );
          console.log("videoId:" + uploadInfo.videoId);
           if(uploadInfo.videoId==null)
            {

          //      var tempic="http://tests.sodataint.com/"+uploadInfo.object;
               
          //      var obj={};
          //      obj.src=tempic;
          //        console.log("uploadtag:"+_this.uploadtag)
          //       if(_this.uploadtag==1)
          //      {
          //      _this.imagelist1.push(obj);

          //      }
          //      if(_this.uploadtag==2)
          //       {
          //        _this.imagelist2.push(obj);
          //       }
          //      if(_this.uploadtag==3)
          //       {
          //        _this.imagelist3.push(obj);

          //       }
          //        if(_this.uploadtag==4)
          //       {
          //              _this.imagelist4.push(obj);

          //       }
          //         if(_this.uploadtag==7)
          //       {
          //              _this.imagelist.push(obj);

          //       }
          //      if(_this.uploadtag==5)
          //       {
          //         console.log("carda:"+_this.carda)
          //          _this.carda=tempic;
          //       }
          //        if(_this.uploadtag==6)
          //       {
          //           _this.cardb=tempic;
          //       }
               
          //          _this.$toast('上传图片完成')
                
          }
          else
          {
        
          var obj={};
        obj.vid=uploadInfo.videoId;
        obj.video=uploadInfo.videoId;
        obj.videourl="http://tests.sodataint.com/"+uploadInfo.object;
        obj.url='';
        //  _this.videolist.push(obj)
        _this.timer=  setInterval(() => {
              _this.getvideo(obj);
         }, 1000);
        
          }
        },
        // 文件上传失败
        onUploadFailed: function(uploadInfo, code, message) {
          _this.$loadingclose();
        _this.$toast('上传失败')
          console.log(
            "onUploadFailed: file:" +
              uploadInfo.file.name +
              ",code:" +
              code +
              ", message:" +
              message
          );
        },
        // 文件上传进度，单位：字节
        onUploadProgress: function(uploadInfo, totalSize, loadedPercent) {
          console.log(
            "onUploadProgress:file:" +
              uploadInfo.file.name +
              ", fileSize:" +
              totalSize +
              ", percent:" +
              Math.ceil(loadedPercent * 100) +
              "%"
          );
          // $("#jindu").html("percent:" + Math.ceil(loadedPercent * 100) + "%");
             _this.$loadingshowjindu(Math.ceil(loadedPercent * 100) + "%")
        },
        // 上传凭证超时
        onUploadTokenExpired: function(uploadInfo) {
          console.log("onUploadTokenExpired");
          //上传方式1  实现时，根据uploadInfo.videoId调用刷新视频上传凭证接口重新获取UploadAuth
          // uploader.resumeUploadWithAuth(uploadAuth);
          // 上传方式2 实现时，从新获取STS临时账号用于恢复上传
          // uploader.resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken, expireTime);
        },
        //全部文件上传结束
        onUploadEnd: function(uploadInfo) {
          console.log("onUploadEnd: uploaded all the files");
        }
      });
    },
    savevideos(){
      console.log('click')
      if(this.videolist.length==0)
      {
        this.$toast('您还未上传短视频')
        return;
      }
      this.$loadingshow();
  addshopvideo(this.videolist).then(res => {
    this.$loadingclose();
                  if(res.code==200)
                  {
                    this.$toast('视频上传成功')
                    location.reload();
                  }else
                  {
                     this.$toast('视频上传失败')
                  }
    

        
          },
          err=>{
             
               this.$loadingclose();
          }
          );
    },
    getvideo(obj){
                getvideoinfo({vid:obj.vid}).then(res => {
                  if(res.code==200)
                  {
                    if(res.result.cover!='null'&&res.result.cover)
                    {
     obj.url=res.result.cover;
     this.videolist.splice(this.videolist.length-1)
     this.videolist.push(obj)
            this.$loadingclose();
     window.clearInterval(this.timer)
       this.$toast("短视频上传完成" );
                    }
                    else{
                      console.log('waiting...')
                    }
                  }else
                  {
                      window.clearInterval(this.timer)
               this.$loadingclose();
                 this.$toast("服务器异常" );
                  }
    

        
          },
          err=>{
              window.clearInterval(this.timer)
               this.$loadingclose();
          }
          );
      

    },
  //  // 返回布尔值
  //   beforeRead(file) {
  //     if (file.type !== 'image/jpeg') {
  //       Toast('请上传 jpg 格式图片');
  //       return false;
  //     }
    
  //     return true;
  //   },

    // 返回 Promise
    // asyncBeforeRead(file) {
    //   return new Promise((resolve, reject) => {
    //     if (file.type !== 'image/jpeg') {
    //       Toast('请上传 jpg 格式图片');
    //       reject();
    //     } else {
    //       resolve();
    //     }
    //   });
    // },

      afterRead(file) {
      // 此时可以自行将文件上传至服务器
      console.log(file);
    },

     showPopup(data) {
            this.popcontent=data;
            // console.log(this.popcontent)
            this.show2 = true;
    },
getimgsrc(data){
      
      this.havesign=true;
       this.uploadImage5=data;
       
      //  console.log("我的图片的地址："+this.imgsrc);
       this.show2 = false;
  

     },
     tijiao()
     {
        if(this.havesign)
            this.uploadqianming(this.uploadImage5);
            else
            this.$toast('您还未签名')
     },
       uploadqianming(base64str){
      
        this.uploadtag=9;
       this.UpladFile(null,base64str);
    },
     UpladFile(fileObj,base64str) {
            // var fileObj = document.getElementById("file").files[0]; // js 获取文件对象
              var form = new FormData(); // FormData 对象
            var isbase64=0;
            // console.log('base64str:'+base64str)
            //  console.log('fileobj:'+fileObj)
            if(base64str)
                  isbase64=1;
            var url =  "/dev-api/mapi/customer/uploadsign" // 接收上传文件的后台地址
            if(fileObj)
            {
          
            form.append("file", fileObj); // 文件对象
            }
            else{
              var dataurl=base64str;
     var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
    u8arr[n] = bstr.charCodeAt(n);
}
var obj = new Blob([u8arr], {type:mime});
 
form.append("file", obj,"xysign.png");
            }


            this.xhr = new XMLHttpRequest();  // XMLHttpRequest 对象
            this.xhr.open("post", url, true); //post方式，url为服务器请求地址，true 该参数规定请求是否异步处理。
            this.xhr.onload = this.uploadComplete; //请求完成
            this.xhr.onerror =  this.uploadFailed; //请求失败
         var _this=this;
            this.xhr.upload.onprogress = this.progressFunction;//【上传进度调用方法实现】
            this.xhr.upload.onloadstart = function(){//上传开始执行方法
              // var  ot = new Date().getTime();   //设置上传开始时间
              //  var  oloaded = 0;//设置上传开始时，以上传的文件大小为0
              _this.show=true;
              // _this.$loadingshow();
              _this.rate=100;
              _this.currentRate=0;
              _this.text='';
               
               
            };

            this.xhr.send(form); //开始上传，发送form数据

        },
   //上传成功响应
          uploadComplete(evt) {
            //服务断接收完文件返回的结果
               this.show=false;
               this.$loadingclose();
            var data = JSON.parse(evt.target.responseText);
            // console.log('服务器响应')
            console.log(data)
            if(data.success) {
              console.log('上传成功')
                // this.$toast("签约成功！");
                this.sign=true;
                sessionStorage.setItem('signpic',data.result)
                // this.uploadImage5=data.result;
                // this.uploadsuccess(data.result);
            }else{
                this.$toast(data.message);
            }

        },
        //上传失败
          uploadFailed(evt) {
                 this.show=false;
                  this.$loadingclose();
            this.$toast("上传失败！");
        },
        //取消上传
          cancleUploadFile(){
                 this.show=false;
                  this.$loadingclose();
            this.xhr.abort();
        },

  //上传进度实现方法，上传过程中会频繁调用该方法
          progressFunction(evt) {
            // var progressBar = document.getElementById("progressBar");
            // var percentageDiv = document.getElementById("percentage");
            // event.total是需要传输的总字节，event.loaded是已经传输的字节。如果event.lengthComputable不为真，则event.total等于0
            if (evt.lengthComputable) {//
                // progressBar.max = evt.total;
                 // progressBar.value = evt.loaded;
                // this.rate=evt.total;
               
                this.currentRate = Math.round(evt.loaded / evt.total * 100);
               
                this.text = Math.round(evt.loaded / evt.total * 100) + "%";
                console.log(this.currentRate)
                  if(evt.loaded==evt.total)
                {
                   this.$loadingshow();
                }
            }
            else
            {
            
            }
             
        },

  }
}
</script>

<style lang="scss" scoped>
.documentation-container {
  // margin: 50px;
  .document-btn {
    float: left;
    margin-left: 50px;
    display: block;
    cursor: pointer;
    background: black;
    color: white;
    height: 60px;
    width: 200px;
    line-height: 60px;
    font-size: 20px;
    text-align: center;
  }
}
   .popstyle{
        width: 100%;
        height: 30%;
    }
    .tjshipin{
      width: 150px;
      height: 40px;
      border-radius: 10px;
      background: cornflowerblue;
      color: #fff;
      font-size:18px;
      text-align: center;
      line-height: 40px;
      margin:0 auto;
      margin-top:50px;
    }
    .uploadarea{
      width:200px;
      height:200px;
      border: 1px #e5e5e5 dashed;
      text-align: center;

    }
    .uploadbtn{
      width:200px;
      height:200px;
      font-size: 50px;
      color: #969799;
      line-height: 200px;
    }
    .videoname{
       margin-top:10px;
       font-size: 16px;
       color: #969799;

    }
</style>
